Imports GeoFramework
Imports GeoFramework.IO
Imports GeoFramework.Gps.Nmea

Public Class AsynchronousDetectingDevicesForm
    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Become notified when device detection starts and stops
        AddHandler Devices.DeviceDetectionAttempted, AddressOf Devices_DeviceDetectionAttempted
        AddHandler Devices.DeviceDetectionStarted, AddressOf Devices_DeviceDetectionStarted
        AddHandler Devices.DeviceDetectionCompleted, AddressOf Devices_DeviceDetectionCompleted

        ' Become notified when a new device is detected
        AddHandler Devices.DeviceDetected, AddressOf Devices_DeviceDetected

        ' Become notified when an exception is thrown
        AddHandler Devices.DeviceDetectionExceptionOccurred, AddressOf Devices_ExceptionOccurred

        ' Has a GPS device already been discovered?
        If Devices.IsDeviceDetected Then
            ' Yes.  Set the property grid to it
            DevicePropertyGrid.SelectedObject = Devices.GetDeviceByProtocol(NmeaInterpreter.ProtocolName)
        Else
            ' No.  Start device detection now
            Devices.Detect()

            ' NOTE: If device detection is already in progress, calling this
            ' method again has no effect.
        End If

        ' Is detection in progress?
        If Devices.IsDetectionInProgress Then
            ' Yes.  Show that we're waiting for a device
            StatusBar.Text = "Detection is in progress, please wait..."
        End If
    End Sub

#Region " When a GPS Device is Detected "

    Private Sub Devices_DeviceDetected(ByVal sender As Object, ByVal e As DeviceEventArgs)
        ' And use Invoke to update the form
        DevicePropertyGrid.SelectedObject = e.Device

        ' Also update the status bar
        StatusBar.Text = "Found device: " + e.Device.ToString()
    End Sub

#End Region

#Region " When an Exception is Thrown During Device Detection "

    Private Sub Devices_ExceptionOccurred(ByVal sender As Object, ByVal e As ExceptionEventArgs)
        ' Raise the exception
        StatusBar.Text = "An exception was encountered during detection."
        MessageBox.Show(e.Exception.ToString())
    End Sub

#End Region

#Region " When Device Detection is Started & Stopped "

    Private Sub Devices_DeviceDetectionStarted(ByVal sender As Object, ByVal e As EventArgs)
        StatusBar.Text = "Starting device detection..."
    End Sub

    Private Sub Devices_DeviceDetectionAttempted(ByVal sender As Object, ByVal e As DeviceEventArgs)
        ' And notify of the detection attempt
        StatusBar.Text = "Attempting detection on " + e.Device.ToString()
    End Sub

    Private Sub Devices_DeviceDetectionCompleted(ByVal sender As Object, ByVal e As EventArgs)
        StatusBar.Text = "Device detection is complete."
    End Sub

#End Region
End Class